package com.qxzn.app.page.util.face;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;

import com.qxzn.app.util.MathUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 文件读取工具类
 */
public class FileUtil {

    public static final String baseApkPath = "apk";
    public static final String baseFilePath = "file";
    public static final String baseAudioPath = "audio";
    public static final String baseImagePath = "image";
    public static final String basePhotoPath = "photo";

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数  
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb，1K=1024B
     *
     * @param bitmap
     * @param maxByte
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap, int maxByte) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            int options = 100;
            while (output.toByteArray().length > maxByte && options != 10) {
                output.reset(); //清空output
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, output);//这里压缩options%，把压缩后的数据存放到output中
                options -= 10;
            }
        } catch (Exception e) {

        }
//        bitmap.recycle();
        return output.toByteArray();
    }

    /**
     * APK下载文件路径
     *
     * @param context
     * @return
     */
    public static String getBaseApkPath(Context context) {
        return context.getExternalFilesDir(baseApkPath).getAbsolutePath();
    }

    /**
     * 存储文件路径
     *
     * @param context
     * @return
     */
    public static String getBaseFilePath(Context context) {
        return context.getExternalFilesDir(baseFilePath).getAbsolutePath();
    }

    /**
     * 存储音频路径
     *
     * @param context
     * @return
     */
    public static String getBaseAudioPath(Context context) {
        return context.getExternalFilesDir(baseAudioPath).getAbsolutePath();
    }

    /**
     * 存储图片路径
     *
     * @param context
     * @return
     */
    public static String getBaseImagePath(Context context) {
        return context.getExternalFilesDir(baseImagePath).getAbsolutePath();
    }

    /**
     * 存储拍照图片路径
     *
     * @param context
     * @return
     */
    public static String getBasePhotoPath(Context context) {
        return context.getExternalFilesDir(basePhotoPath).getAbsolutePath();
    }

    public static boolean deleteFile(File file) {
        if (file != null && file.exists() && !file.isDirectory()) {
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 获取文件夹所占用的存储空间的大小
     *
     * @param file
     * @return
     */
    public static int getDirectoryFileSize(File file) {
        int size = 0;
        if (file != null && file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File subFile : files) {
                    if (subFile.isDirectory()) {
                        size += getDirectoryFileSize(subFile);
                    } else {
                        size += subFile.length();
                    }
                }
            }
        }
        return size;
    }

    /**
     * 获取音视频文件时长
     *
     * @return
     */
    public static long getFileDuration(String videoPath) {
        long duration = 0;
        try {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(videoPath);
            duration = MathUtil.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return duration;
    }

}
